<template>
    <el-card class="box-card" style="border-right: none; border-bottom: none !important; border-top: none !important;border-radius: 0;">
      <div class="card-header">
        <span>文章管理</span>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </div>
      <el-form :inline="true" :model="formInline" class="form-inline">
      <el-form-item label="名称">
        <el-input v-model="formInline.title" placeholder="名称" clearable />
      </el-form-item>

      <el-form-item label="分类">
        <el-select
          v-model="formInline.categoryId"
          placeholder="分类"
          clearable
        >
          <el-option v-for="item in articleCategoryAllList" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select
          v-model="formInline.state"
          placeholder="状态"
          clearable
        >
          <el-option label="全部" :value=null />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="lists" height="580px" v-loading="loading" style="width: 100%">
        <!-- 渲染标题 -->
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column prop="category.name" label="分类" min-width="150" />
        <!-- 渲染封面图 -->
        <el-table-column label="封面图" min-width="150">
        <template #default="scope">
            <img :src="scope.row.cover" alt="封面图" style="width: 50px; height: 50px; border-radius: 50%;" />
        </template>
        </el-table-column>

        <!-- 渲染状态 -->
        <el-table-column label="状态" min-width="100">
        <template #default="scope">
            <el-tag :type="scope.row.status === 1 ?'success' :'danger'" >{{scope.row.status_text}}</el-tag>
        </template>
        </el-table-column>

        <!-- 排序 -->
        <el-table-column prop="sort" label="排序" min-width="150" />

        <!-- 渲染创建时间 -->
        <el-table-column prop="created_at" label="创建时间" width="160" />

        <!-- 渲染更新时间 -->
        <el-table-column prop="updated_at" label="更新时间" width="160" />

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" width="200" >
        <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <!-- <el-button size="small" @click="handleView(scope.$index, scope.row)">查看</el-button> -->
        </template>
        </el-table-column>
    </el-table>

    <el-pagination class="el-p"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
  </el-card>

  <!-- 新增/编辑管理员对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增文章' : '编辑文章'"
    width="900px"
    top="50px"
    :close-on-click-modal="false"
  >
    <AddArticleForm ref="addFormRef" :form-data="currentFormData" :is-edit="dialogType === 'edit'" :articleCategoryList="articleCategoryList" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref,reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { articleCategoryService } from "@/api/articleCategoryService";
import { articleService } from '@/api/articleService';
import AddArticleForm from '@/components/AddArticleForm.vue';

const currentPage = ref(1)  // 默认第一页
const pageSize = ref(10)    // 默认每页10条
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialogVisible = ref(false);
const total = ref(0);
const dialogType = ref('add');//弹出框类型 add 添加 edit编辑
const currentFormData = ref(null);
const addFormRef = ref(null);
const articleCategoryList = ref([]);
const articleCategoryAllList = ref([]);
const loading = ref(false); // 控制加载状态

const formInline = reactive({
    title: '',
    state: '',
    categoryId: ''
});
const lists = ref([]);

//查看分类列表 启用未删除的数据
const getArticleCategoryList =  async () => {
    articleCategoryService.getAllList({status:1}).then(res => {
        articleCategoryList.value = res;
    });
}
//查看所有分类列表 包括软删除的数据
const getArticleCategoryAllList =  async () => {
    articleCategoryService.getAllList().then(res => {
        articleCategoryAllList.value = res;
    });
}

const getList = async () => {
    loading.value = true; // 开始加载数据
    try {
      const params = {
        title: formInline.title,
        status: formInline.state,
        page: currentPage.value,
        pageSize: pageSize.value,
        category_id: formInline.categoryId
      };
      const response = await articleService.getList(params);
      lists.value = response.data || [];
      total.value = response.total || 0;
    } catch (error) {
      ElMessage.error('获取列表失败');
      lists.value = [];
      total.value = 0;
    }

    loading.value = false; // 开始加载数据
}
getArticleCategoryList(); // 获取任务类列表
getArticleCategoryAllList(); // 获取所有任务类列表
getList(); // 获取列表数据

//分页选择数量
const handleSizeChange = (val) => {
    pageSize.value = val;
    getList();
}

//指定页码
const handleCurrentChange = (val) => {
    currentPage.value = val;
    getList();
}

//重置查询条件
const resetForm = () => {
    formInline.name = '';
    formInline.state = '';
    formInline.categoryId='';
    getList();
}

//编辑
const handleEdit = (index, row) => {
    dialogVisible.value = true;
    dialogType.value = 'edit';
    currentFormData.value = row;
}

//
const handleDelete = (row) => {
    ElMessageBox.confirm('是否删除该文章?', '提示', {
        type: 'warning'
    }).then(async () => {
        const res = await articleService.del(row.id);
        console.log(res);
        if (res.data.code === 1) {
            ElMessage.success('删除成功');
            getList();
        } else {
            ElMessage.error(res.msg);
        }

    }).catch(() => {});
}

//搜索
const onSearch = () => {
    getList();
};

//重置搜索条件
const resetDialog = () => {
    dialogType.value = 'add';
    currentFormData.value = null;
    if (addFormRef.value) {
      addFormRef.value.resetForm();
    }
};

 // 监听对话框关闭事件
 watch(dialogVisible, (newVal) => {
    if (!newVal) {
      resetDialog();
    }
  });

const submitForm = async () => {
    // 检查表单引用是否存在
    if (!addFormRef.value) return;

    // 验证表单数据合法性
    const isValid = await addFormRef.value.validateForm();
    // 如果表单数据不合法，则终止操作
    if (!isValid) return;

    try {
      // 复制表单数据
      const formData = { ...addFormRef.value.form };

      // 根据dialogType的值决定是添加还是更新管理员信息
      if (dialogType.value === 'add') {
        // 添加管理员
        await articleService.add(formData);
        ElMessage.success('新增任务成功');
      } else {
        // 更新管理员信息
        await articleService.update(formData.id,formData);
        ElMessage.success('更新任务成功');
      }

      // 关闭对话框
      dialogVisible.value = false;
      // 刷新列表
      getList();
    } catch (error) {
      // 处理添加或更新操作失败的情况
      //ElMessage.error(dialogType.value === 'add' ? '新增管理员失败' : '更新管理员失败');
    }
};
</script>
<style scoped>
  .form-inline {
    margin: 20px 0;
    border-bottom: 1px solid #e4e7ed;
  }
  .el-p{
    margin-top: 15px;
    display: flex;
    justify-self: flex-end;
  }
  .el-select{
    width: 100px;
  }
  .card-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid #e4e7ed;

  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  .el-descriptions {
    margin: 20px;
  }

</style>
